package com.example.voucher.config.util;

import java.math.BigDecimal;
import java.math.RoundingMode;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BigDecimalHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(BigDecimalHandler.class);

    private BigDecimalHandler() {}

    public static BigDecimal dealNull(BigDecimal num) {
        return num == null ? BigDecimal.ZERO : num;
    }

    public static BigDecimal setScale(BigDecimal num) {
        return num == null ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP) : num.setScale(2, RoundingMode.HALF_UP);
    }

    public static BigDecimal setScale(BigDecimal num, int newScale) {
        return num == null ? BigDecimal.ZERO.setScale(newScale, RoundingMode.HALF_UP)
            : num.setScale(newScale, RoundingMode.HALF_UP);
    }

    public static BigDecimal setScale(BigDecimal num, int newScale, int roundingMode) {
        return num == null ? BigDecimal.ZERO.setScale(newScale, roundingMode) : num.setScale(newScale, roundingMode);
    }
    
    public static BigDecimal divide(BigDecimal num, BigDecimal divisor, int newScale) {
        return dealNull(num).divide(dealNull(divisor), newScale, RoundingMode.HALF_UP);
    }

    public static String toPlainString(BigDecimal num) {
        return num == null ? "" : num.toPlainString();
    }

    public static String toPlainString(BigDecimal num, int newScale) {
        num = setScale(num, newScale);
        return num == null ? "" : num.toPlainString();
    }

    public static String stripTrailingZeros(BigDecimal num) {
        return num == null ? "" : num.stripTrailingZeros().toPlainString();
    }

    public static String stripTrailingZeros(BigDecimal num, int newScale) {
        num = setScale(num, newScale);
        return num == null ? "" : num.stripTrailingZeros().toPlainString();
    }
    
    public static String divideAndStripTrailingZeros(BigDecimal num, BigDecimal divisor, int newScale) {
        return dealNull(num).divide(dealNull(divisor), newScale, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
    }

}
